package com.boarsoft.boar.soagov.monitor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.boarsoft.boar.sys.SysParamBiz;
import com.boarsoft.boar.sys.entity.SysParam;
import com.boarsoft.common.util.JsonUtil;
import com.boarsoft.flow.core.SimpleFlowEngine;
import com.boarsoft.message.bean.Message;
import com.boarsoft.message.core.MessageService;
import com.boarsoft.soagov.bean.MonitorData;

@Component("monitorService")
public class MonitorServiceImpl implements MonitorService, MessageService {
	private static final Logger log = LoggerFactory.getLogger(MonitorServiceImpl.class);

	@Autowired
	protected SysParamBiz sysParamBiz;
	@Autowired
	protected SimpleFlowEngine flowEngine;

	@Override
	public void put(Message msg) {
		log.info("Received message: {}", JsonUtil.toJSONString(msg));
		// 根据监控数据对象的type属性，决定如何处理
		this.put((MonitorData) msg.getContent());
	}

	@Override
	public void put(MonitorData md) {
		// 根据事件类型，执行预定的处理流程
		String k = new StringBuilder("soagov.event.")//
				.append(md.getKey()).append(".flowId").toString();
		SysParam sp = sysParamBiz.get(k);
		if (sp == null) {
			log.error("Can not find sys param {}", k);
			return;
		}
		String flowId = sp.getValue();
		// TODO 将数据记入监控中心数据库
		log.info("Start flow {} to handle monitor event {}", flowId, md.getId());
		try {
			flowEngine.start(flowId, md);
		} catch (Throwable e) {
			log.error("Error on start flow {} for monitor event {}", flowId, md.getId(), e);
		}
	}
}